from .db_context import DBConnection
from ..model.submit_record import SubmitRecord


async def insert_record(assignment_id, stu_id_list):
    conn = DBConnection().connection
    cur = conn.cursor()
    for stu_id in stu_id_list:
        cur.execute("INSERT INTO SubmitRecord (assignmentId, studentId, uploaded) VALUES(?,?,?)",
                (assignment_id, stu_id[0], 0))

    cur.close()
    conn.commit()
    
async def modify_record(assignment_id, stu_id):
    conn = DBConnection().connection
    cur = conn.cursor()
    cur.execute('''UPDATE SubmitRecord set uploaded = 1 
                WHERE assignmentId=? AND studentId=?''',
                (assignment_id, stu_id))
    
    cur.close()
    conn.commit()


async def get_submit_record(assignment_id):
    conn = DBConnection().connection
    cur = conn.cursor()
    cur.execute('''
    SELECT SubmitRecord.studentId, SubmitRecord.uploaded, U.name
    FROM SubmitRecord LEFT OUTER JOIN User U on SubmitRecord.studentId = U.studentId
    WHERE assignmentId = ?
    ''', [assignment_id])
    records = list(map(lambda x: SubmitRecord(assignment_id, x[0], bool(x[1]), str(x[2])), cur.fetchall()))
    return records
